package com.gxz.logbacktest.controller;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.gxz.logbacktest.config.LogInfo;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping(value = {"/log"})
public class TestLogController {

    // @Autowired
    // private LogInfo testLog;
    private LogInfo logInfo = new LogInfo();

    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String addr;

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Autowired
    private DiscoveryClient discoveryClient;

    private String MSG = RandomUtil.randomString(64);

    @GetMapping(value = "/sleep")
    public String sleep() throws InterruptedException {
        Thread.sleep(60000);
        return "成功返回！";
    }

    @GetMapping(value = "/success")
    public String success() {
        // log.info(StrUtil.format("还是请求进来了:ip:{};port:{}", nacosDiscoveryProperties.getIp(),
        //     nacosDiscoveryProperties.getPort()));
        return "成功返回！";
    }

    @GetMapping(value = "/success100")
    public String success100() throws InterruptedException {
        Thread.sleep(100);
        return "成功返回！";
    }

    @GetMapping(value = "/success500")
    public String success500() throws InterruptedException {
        Thread.sleep(500);
        return "成功返回！";
    }

    @GetMapping(value = "/success2000")
    public String success2000() throws InterruptedException {
        Thread.sleep(2000);
        return "成功返回！";
    }

    @GetMapping(value = "/close")
    public String close() {
        RestTemplate restTemplate = new RestTemplate();

        String url = "http://{}/nacos/v2/ns/instance?serviceName={}&ip={}&port={}&namespaceId=dev&enabled=false";
        List<ServiceInstance> instances = discoveryClient.getInstances("logback-Test");
        String ip = nacosDiscoveryProperties.getIp();
        log.error(StrUtil.format("请求了colse接口:ip:{};port:{}", ip, nacosDiscoveryProperties.getPort()));
        instances.forEach(item -> {
            if (item.getHost().equals(ip) && item.getPort() == nacosDiscoveryProperties.getPort()) {
                HttpEntity<String> httpEntity = new HttpEntity<>("", new HttpHeaders());
                String format = StrUtil.format(url, addr, item.getServiceId(), item.getHost(), item.getPort());
                String body = restTemplate.exchange(format, HttpMethod.PUT, httpEntity, String.class).getBody();
                log.error("请求地址：" + format + "结果是：" + body);
            }
        });
        // Thread.sleep(35000);
        return "成功返回！";
    }

    @GetMapping(value = "/errorLog")
    public String errorLog() {
        log.error(MSG);
        return "成功返回！";
    }

    @GetMapping(value = "/total")
    public String errorLog(HttpServletRequest httpServletRequest) {
        String queryString = httpServletRequest.getQueryString();
        try {
            Integer value = Integer.valueOf(queryString);
            MSG = RandomUtil.randomString(value * 1024);
            log.info("修改了日志大小");
        } catch (Exception ignored) {
        }
        return "成功返回！";
    }

    AtomicInteger value = new AtomicInteger();

    @GetMapping(value = "/copyValue")
    public String copyValue() {
        // 源文件路径
        Path sourcePath = Paths.get("/logs/logback-Test/project_info.log");
        // 目标文件路径
        Path destinationPath = Paths.get(StrUtil.format("/logs/logback-Test/project_info_{}.log", value.addAndGet(1)));

        try {
            // 使用Files.copy()方法复制文件
            // StandardCopyOption.REPLACE_EXISTING选项表示如果目标文件已存在，则替换它
            Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
            log.info("文件复制成功！");
        } catch (IOException e) {
            // 处理异常，例如文件不存在或无法访问等
            log.error("复制失败！", e);
        }
        return "成功返回！";
    }
}
